package com.naiterui.ehp.bs.im.utils;

import java.util.ArrayList;

import org.im4java.core.ConvertCmd;
import org.im4java.core.IMOperation;
import org.im4java.core.IdentifyCmd;
import org.im4java.process.ArrayListOutputConsumer;
import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

/**
 * 图片缩放,图片合成 工具
 */
public class ImageUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(ImageUtils.class);

    /**
     * 根据尺寸缩放图片
     *
     * @param width   缩放后的图片宽度
     * @param height  缩放后的图片高度
     * @param srcPath 源图片路径
     * @param newPath 缩放后图片的路径
     */
    public static void zoomImage(Integer width, Integer height, String srcPath, String newPath) {
        try {
            IMOperation op = new IMOperation();
            op.addImage(srcPath);
            if (width == null) {// 根据高度缩放图片
                op.resize(null, height);
            } else if (height == null) {// 根据宽度缩放图片
                op.resize(width, null);
            } else {
                op.resize(width, height);
            }
            op.addImage(newPath);
            ConvertCmd cmd = new ConvertCmd(true);

            setOS(cmd);

            System.out.println(op.toString());

            cmd.run(op);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
    }

    public static void zoomImage(String srcPath, String newPath) {
        try {
            IMOperation op = new IMOperation();
            op.addImage(srcPath);
            int width = getWidth(srcPath);
            int height = getHeight(srcPath);
            if (width > 230 || height > 240) {
                width = 230;
                height = 240;
            }
            op.resize(width, height);
            op.addImage(newPath);
            ConvertCmd cmd = new ConvertCmd(true);

            setOS(cmd);

            cmd.run(op);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
    }

    /**
     * 图片合成
     *
     * @param args
     * @param maxWidth
     * @param maxHeight
     * @param newpath
     * @param mrg
     * @param type      1:横,2:竖
     */
    public static void montage(String[] args, Integer maxWidth, Integer maxHeight, String newpath, Integer mrg, String type) throws Exception {

        IMOperation op = new IMOperation();
        ConvertCmd cmd = new ConvertCmd(true);
        String thumb_size = maxWidth + "x" + maxHeight + "^";
        String extent = maxWidth + "x" + maxHeight;
        if ("1".equals(type)) {
            op.addRawArgs("+append");
        } else if ("2".equals(type)) {
            op.addRawArgs("-append");
        }

        op.addRawArgs("-thumbnail", thumb_size);
        op.addRawArgs("-gravity", "center");
        op.addRawArgs("-extent", extent);

        Integer border_w = maxWidth / 40;
        op.addRawArgs("-border", border_w + "x" + border_w);
        op.addRawArgs("-bordercolor", "#ccc");

        op.addRawArgs("-border", 1 + "x" + 1);
        op.addRawArgs("-bordercolor", "#fff");

        for (String img : args) {
            op.addImage(img);
        }
        if ("1".equals(type)) {
            Integer whole_width = ((mrg / 2) + 1 + border_w + maxWidth + border_w + (mrg / 2) + 1) * args.length - mrg;
            Integer whole_height = maxHeight + border_w + 1;
            op.addRawArgs("-extent", whole_width + "x" + whole_height);
        } else if ("2".equals(type)) {
            Integer whole_width = maxWidth + border_w + 1;
            Integer whole_height = ((mrg / 2) + 1 + border_w + maxHeight + border_w + (mrg / 2) + 1) * args.length - mrg;
            op.addRawArgs("-extent", whole_width + "x" + whole_height);
        }
        op.addImage(newpath);

        setOS(cmd);

        cmd.run(op);

    }

    public static int getWidth(String imagePath) {
        int width = 0;
        try {
            IMOperation op = new IMOperation();
            op.format("%w"); // 设置获取宽度参数
            op.addImage(1);
            IdentifyCmd identifyCmd = new IdentifyCmd(true);
            ArrayListOutputConsumer output = new ArrayListOutputConsumer();
            identifyCmd.setOutputConsumer(output);
            identifyCmd.run(op, imagePath);
            ArrayList<String> cmdOutput = output.getOutput();
            assert cmdOutput.size() == 1;
            width = Integer.parseInt(cmdOutput.get(0));
        } catch (Exception e) {
            width = 0;
            LOGGER.error("[getWidth][运行指令出错!", e);
            System.out.println("运行指令出错!");
        }
        return width;
    }

    public static int getHeight(String imagePath) {
        int height = 0;
        try {
            IMOperation op = new IMOperation();
            op.format("%h"); // 设置获取宽度参数
            op.addImage(1);
            IdentifyCmd identifyCmd = new IdentifyCmd(true);
            ArrayListOutputConsumer output = new ArrayListOutputConsumer();
            identifyCmd.setOutputConsumer(output);
            identifyCmd.run(op, imagePath);
            ArrayList<String> cmdOutput = output.getOutput();
            assert cmdOutput.size() == 1;
            height = Integer.parseInt(cmdOutput.get(0));
        } catch (Exception e) {
            height = 0;
            System.out.println("运行指令出错!");
        }
        return height;
    }

    /**
     * 根据不同系统设置
     *
     * @param cmd
     */
    private static void setOS(ConvertCmd cmd) {
        String osName = System.getProperty("os.name").toLowerCase();
        if (osName.indexOf("win") != -1) {
            // linux下不要设置此值，不然会报错
            cmd.setSearchPath("d://Program Files//GraphicsMagick-1.3.21-Q16");
        }
    }

}
